<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>OSS文件上传</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/ali-oss@6.18.0/dist/aliyun-oss-sdk.min.js"></script>

    <!--导入sdk文件-->
    <script
            type="text/javascript"
            src="../templates/h5/assets/aliyun-oss-sdk-6.18.0.min.js"
    ></script>

    <script src="../templates/h5/assets/jquery.min.js"></script>
    <script src="../templates/h5/assets/vconsole.min.js"></script>
    <script>
        // var vConsole = new VConsole();
        // console.log('Hello world');
    </script>

    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f7fa;
            color: #333;
        }
        .container {
            background-color: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #1e88e5;
            text-align: center;
            margin-bottom: 30px;
        }
        .upload-area {
            border: 2px dashed #1e88e5;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            background-color: #f8fdff;
            transition: all 0.3s;
            cursor: pointer;
        }
        .upload-area:hover {
            background-color: #e3f2fd;
            border-color: #1565c0;
        }
        .upload-area.highlight {
            background-color: #e3f2fd;
            border-color: #1565c0;
            transform: scale(1.01);
        }
        .file-input {
            display: none;
        }
        .upload-btn {
            background-color: #1e88e5;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: background-color 0.3s;
            margin-top: 15px;
            width: 100%;
        }
        .upload-btn:hover {
            background-color: #1565c0;
        }
        .upload-btn:disabled {
            background-color: #90caf9;
            cursor: not-allowed;
        }
        .file-info {
            margin-top: 15px;
            padding: 10px;
            background-color: #e3f2fd;
            border-radius: 5px;
            display: none;
        }
        .progress-container {
            margin-top: 20px;
            display: none;
        }
        .progress-bar {
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        .progress {
            height: 100%;
            background-color: #1e88e5;
            width: 0%;
            transition: width 0.3s;
        }
        .message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
        }
        .info {
            background-color: #e3f2fd;
            color: #0d47a1;
        }
        .success {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
        .error {
            background-color: #ffebee;
            color: #c62828;
        }
        .warning {
            background-color: #fff8e1;
            color: #f57f17;
        }
        .status {
            margin-top: 15px;
            font-weight: 500;
        }
        .icon {
            font-size: 48px;
            color: #1e88e5;
            margin-bottom: 15px;
        }
        .debug-info {
            margin-top: 20px;
            padding: 15px;
            background-color: #f5f5f5;
            border-radius: 5px;
            font-size: 12px;
            display: none;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>OSS文件上传</h1>

    <div class="upload-area" id="uploadArea">
        <div class="icon">📁</div>
        <h3>点击选择文件或拖拽文件到此处</h3>
        <p>支持单个文件上传，最大文件大小为5GB</p>
        <input type="file" id="file" class="file-input"/>
    </div>

    <div class="file-info" id="fileInfo"></div>

    <div class="progress-container" id="progressContainer">
        <div class="progress-bar">
            <div class="progress" id="progressBar"></div>
        </div>
        <div class="status" id="progressText">0%</div>
    </div>

    <button class="upload-btn" id="submit" disabled>开始上传</button>

    <div class="message" id="message"></div>

    <div class="debug-info" id="debugInfo"></div>

    <button id="toggleDebug" style="margin-top: 10px; background: none; border: none; color: #666; cursor: pointer;">
        显示调试信息
    </button>
</div>

<script type="text/javascript">
    let ossClient = null;
    let isInitialized = false;

    // 显示调试信息
    function showDebugInfo(info) {
        const debugEl = $('#debugInfo');
        debugEl.append(`<div>${new Date().toLocaleTimeString()}: ${info}</div>`);
    }

    // 初始化OSS客户端
    async function initOSSClient() {
        return new Promise((resolve, reject) => {
            showDebugInfo('开始初始化OSS客户端...');

            $.ajax({
                url: '/oss/getStsToken',
                type: 'GET',
                dataType: 'json',
                timeout: 10000,
                success: function(response) {
                    showDebugInfo('STS Token请求成功');

                    if (response.code === 0) {
                        try {
                            showMessage('正在获取STS Token...', 'info');
                            const stsData = response.data;

                            showDebugInfo(`获取到STS Token，region: ${stsData.region}, bucket: ${stsData.bucket}`);

                            // 创建OSS客户端实例 - 使用更简单的配置
                            ossClient = new OSS({
                                region: stsData.region || "oss-cn-beijing",
                                accessKeyId: stsData.accessKeyId,
                                accessKeySecret: stsData.accessKeySecret,
                                stsToken: stsData.securityToken,
                                bucket: stsData.bucket || "xjksii81ks",
                                secure: true, // 使用HTTPS
                                timeout: 60000, // 增加超时时间
                                // 移除复杂的refreshSTSToken配置，简化初始版本
                            });

                            isInitialized = true;
                            showMessage('OSS客户端初始化成功', 'success');
                            showDebugInfo('OSS客户端初始化完成');
                            resolve(ossClient);
                        } catch (error) {
                            console.error('初始化OSS客户端失败:', error);
                            showDebugInfo(`初始化失败: ${error.message}`);
                            showMessage('初始化失败: ' + error.message, 'error');
                            reject(error);
                        }
                    } else {
                        const errorMsg = response.msg || '获取STS Token失败';
                        showDebugInfo(`STS Token获取失败: ${errorMsg}`);
                        showMessage(errorMsg, 'error');
                        reject(new Error(errorMsg));
                    }
                },
                error: function(xhr, status, error) {
                    const errorMsg = '请求失败: ' + (error || status || '网络错误');
                    showDebugInfo(`STS Token请求错误: ${errorMsg}`);
                    showMessage(errorMsg, 'error');
                    reject(new Error(errorMsg));
                }
            });
        });
    }

    // 显示消息
    function showMessage(message, type = 'info') {
        const messageEl = $('#message');
        messageEl.removeClass('info success error warning').addClass(type).text(message).show();
    }

    // 更新上传进度
    function updateProgress(percentage) {
        const progressBar = $('#progressBar');
        const progressText = $('#progressText');
        const progressContainer = $('#progressContainer');

        const progress = Math.round(percentage * 100);
        progressBar.css('width', `${progress}%`);
        progressText.text(`${progress}%`);

        if (progress < 100) {
            progressContainer.show();
        } else {
            setTimeout(() => {
                progressContainer.hide();
            }, 2000);
        }
    }

    // 生成唯一的文件名
    function generateFileName(originalName) {
        const timestamp = new Date().getTime();
        const random = Math.random().toString(36).substring(2, 8);
        const extension = originalName.split('.').pop();
        return `uploads/${timestamp}_${random}.${extension}`;
    }

    // 简单的上传函数 - 不使用分片上传
    async function simpleUpload(file, fileName) {
        showDebugInfo(`开始简单上传: ${fileName}`);

        try {
            const result = await ossClient.put(fileName, file, {
                headers: {
                    "Cache-Control": "no-cache",
                    "x-oss-forbid-overwrite": "false", // 改为false允许覆盖
                },
                meta: {
                    uploadTime: new Date().toISOString(),
                    source: 'web-upload'
                }
            });

            showDebugInfo(`简单上传成功: ${result.url}`);
            return result;
        } catch (error) {
            showDebugInfo(`简单上传失败: ${error.message}`);
            throw error;
        }
    }

    // 分片上传函数
    async function multipartUpload(file, fileName) {
        showDebugInfo(`开始分片上传: ${fileName}, 大小: ${file.size} bytes`);

        const uploadOptions = {
            progress: (p, checkpoint, res) => {
                console.log('上传进度:', p);
                showDebugInfo(`上传进度: ${Math.round(p * 100)}%`);
                updateProgress(p);
            },
            parallel: 4,
            partSize: 1024 * 1024, // 1MB
            timeout: 120000, // 2分钟超时
            headers: {
                "Cache-Control": "no-cache",
                "x-oss-forbid-overwrite": "false", // 改为false允许覆盖
            },
            meta: {
                uploadTime: new Date().toISOString(),
                source: 'web-upload'
            }
        };

        try {
            const result = await ossClient.multipartUpload(fileName, file, uploadOptions);
            showDebugInfo(`分片上传成功: ${result.name}`);
            return result;
        } catch (error) {
            showDebugInfo(`分片上传失败: ${error.message}`);
            throw error;
        }
    }

    // 上传文件
    async function uploadFile(file) {
        try {
            if (!ossClient || !isInitialized) {
                showMessage('正在初始化OSS客户端...', 'info');
                await initOSSClient();
            }

            const fileName = generateFileName(file.name);
            showMessage(`开始上传文件: ${fileName}`, 'info');
            showDebugInfo(`准备上传文件: ${file.name} -> ${fileName}`);

            let result;

            // 根据文件大小选择上传方式
            if (file.size < 10 * 1024 * 1024) { // 小于10MB使用简单上传
                showDebugInfo('使用简单上传方式');
                result = await simpleUpload(file, fileName);
            } else {
                showDebugInfo('使用分片上传方式');
                result = await multipartUpload(file, fileName);
            }

            console.log('上传成功:', result);
            showMessage(`文件上传成功! 文件名: ${fileName}`, 'success');
            $('#submit').prop('disabled', true);
            showDebugInfo('上传流程完成');

            return result;
        } catch (error) {
            console.error('上传失败:', error);

            // 更详细的错误信息
            let errorMessage = '上传失败: ' + error.message;
            if (error.name === 'RequestError') {
                errorMessage = '网络连接错误，请检查网络连接或稍后重试';
            } else if (error.code === 'AccessDenied') {
                errorMessage = '权限不足，请检查STS Token权限';
            } else if (error.code === 'NoSuchBucket') {
                errorMessage = 'Bucket不存在，请检查配置';
            }

            showMessage(errorMessage, 'error');
            showDebugInfo(`上传错误详情: ${error.name} - ${error.code} - ${error.message}`);
            throw error;
        }
    }

    // 页面加载完成后初始化
    $(document).ready(function() {
        // 切换调试信息显示
        $('#toggleDebug').on('click', function() {
            const debugEl = $('#debugInfo');
            if (debugEl.is(':visible')) {
                debugEl.hide();
                $(this).text('显示调试信息');
            } else {
                debugEl.show();
                $(this).text('隐藏调试信息');
            }
        });

        // 预初始化OSS客户端
        showDebugInfo('页面加载完成，开始预初始化');
        initOSSClient().catch(error => {
            console.log('预初始化失败，将在上传时重新初始化');
            showDebugInfo('预初始化失败: ' + error.message);
        });

        // 监听上传按钮点击
        $('#submit').on('click', async function() {
            const fileInput = $('#file')[0];
            const files = fileInput.files;

            if (!files || files.length === 0) {
                showMessage('请选择要上传的文件', 'warning');
                return;
            }

            const file = files[0];

            // 检查文件大小（限制为5GB）
            if (file.size > 5 * 1024 * 1024 * 1024) {
                showMessage('文件大小超过5GB限制', 'error');
                return;
            }

            // 禁用上传按钮
            $('#submit').prop('disabled', true);
            showDebugInfo('开始上传流程');

            try {
                await uploadFile(file);
            } catch (error) {
                console.error('上传过程出错:', error);
                $('#submit').prop('disabled', false);
            }
        });

        // 监听文件选择变化
        $('#file').on('change', function() {
            const files = this.files;
            const fileInfo = $('#fileInfo');
            const submitBtn = $('#submit');

            if (files && files.length > 0) {
                const file = files[0];
                const fileSize = (file.size / 1024 / 1024).toFixed(2);

                fileInfo.html(`
                        <strong>文件信息:</strong><br>
                        名称: ${file.name}<br>
                        大小: ${fileSize} MB<br>
                        类型: ${file.type || '未知'}
                    `).show();

                submitBtn.prop('disabled', false);
                showDebugInfo(`文件已选择: ${file.name}, 大小: ${fileSize} MB`);
            } else {
                fileInfo.hide();
                submitBtn.prop('disabled', true);
            }
        });

        // 拖拽上传功能
        const uploadArea = $('#uploadArea');

        // 阻止默认拖放行为
        $(document).on('dragover drop', function(e) {
            e.preventDefault();
        });

        // 拖拽事件处理
        uploadArea.on('dragover', function() {
            uploadArea.addClass('highlight');
        });

        uploadArea.on('dragleave', function() {
            uploadArea.removeClass('highlight');
        });

        uploadArea.on('drop', function(e) {
            e.preventDefault();
            uploadArea.removeClass('highlight');

            const files = e.originalEvent.dataTransfer.files;
            if (files.length > 0) {
                $('#file').prop('files', files);
                $('#file').trigger('change');
                showDebugInfo(`拖拽文件: ${files[0].name}`);
            }
        });

        // 点击上传区域触发文件选择
        uploadArea.on('click', function() {
            $('#file').click();
        });
    });
</script>
</body>
</html>